package com.anxin.confirmnotificationsrv;

import com.anxin.common.utils.IdGen;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.sys.system.entity.SysUser;
import com.anxin.sys.system.utils.ConfigUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

public final class OSB_BP_WFP_HQ_ImportConfirmNotificationSrvClient {

    /**
     * 获取本系统的token信息
     *
     * @return 系统的token信息
     * @date 2018年5月18日 下午3:23:12
     */
    public static String getApptToken() {
        // 填写自己的系统的token值
        String token = UserUtils.getToken();
//        String token = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjcwMzhhMGNjLThmMDgtNGQxNC1iYTQ4LTIwYmU0NDgxMjk0ZiJ9.sSj9nQji79qxaX0JSFUh5UtmQ85jI6lNfRQxpWtxHh0Gn_xzQbGXjQ6Q89ThGP5Gl3uWHq5V-wWx3g0JfiT-aQ";
        if (token != null && !"".equals(token)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            String md5Str = token + date;
            String md5 = getMD5ForString(md5Str);
            return md5;
        }
        return null;
    }

    /**
     * 字符串MD5计算
     *
     * @param str
     *            字符串
     * @return 计算后的字符串
     */
    public static String getMD5ForString(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            String md5 = new BigInteger(1, md.digest()).toString(16);
            // BigInteger会把0省略掉，需补全至32位
            return fillMD5(md5);
        } catch (Exception e) {
            throw new RuntimeException("MD5加密错误:" + e.getMessage(), e);
        }
    }

    /**
     * 将字符串填补为32位
     *
     * @param md5
     *            MD5字符串
     * @return 填补后的字符串
     */
    private static String fillMD5(String md5) {
        return md5.length() == 32 ? md5 : fillMD5("0" + md5);
    }

    /**
     * 将日期对象转换成xml日期格式
     *
     * @param date
     *            需要转换的日期对象
     * @retur xml日期格式
     */
    private static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date) {
        if (date == null) {
            return null;
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        XMLGregorianCalendar gc = null;
        try {
            gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        } catch (Exception e) {
            System.out.println("日期转化出错！" + e.getMessage());
        }
        return gc;
    }

    /**
     *
     * 构建MSGHEADER对象
     */
    public static InputParameters buildMSGHEADER(String taskId,String processKey) {
        SysUser user = UserUtils.getUser();
        InputParameters inputParameters = new InputParameters();
        // 业务系统根据自己系统的信息填写
        MSGHEADER msgHeader = new MSGHEADER();
        XMLGregorianCalendar gc = convertToXMLGregorianCalendar(new Date());
        msgHeader.setSOURCESYSTEMID("XXJS-GQTZ");
        msgHeader.setSOURCESYSTEMNAME("XXJS-股权投资管理系统");
        msgHeader.setTOKEN(getApptToken());
        msgHeader.setPROVINCECODE("CAP");
        msgHeader.setSUBMITDATE(gc);
        msgHeader.setUSERID(user.getDeputyAccountNumber());
        msgHeader.setUSERNAME(user.getNickName());
        msgHeader.setROUTECODE(ConfigUtils.get("router_code"));
        inputParameters.setMSGHEADER(msgHeader);

        INPUTCOLLECTION inputcollection = new INPUTCOLLECTION();
        List<INPUTCOLLECTIONITEM> list=new ArrayList<INPUTCOLLECTIONITEM>();
        INPUTCOLLECTIONITEM inputcollectionitem = new INPUTCOLLECTIONITEM();
        inputcollectionitem.setPRIKEY(processKey);
        inputcollectionitem.setUSERID(user.getDeputyAccountNumber());
        inputcollectionitem.setNOTIFICATIONID(taskId);
        inputcollectionitem.setREQUESTID(IdGen.uuid());
        inputcollectionitem.setTENANTID("GQTZ");
        inputcollectionitem.setBPMPROVINCE("hq");
        inputcollectionitem.setBPMMETHOD("ImportConfirmNotificatRouteSrv");
        list.add(inputcollectionitem);
        inputcollection.setInputcollectionitem(list);

        inputParameters.setINPUTCOLLECTION(inputcollection);
        return inputParameters;
    }

    /**
     *
     * 构建服务客户端
     *
     */
    public static OSBBPWFPHQImportConfirmNotificationSrv buildServiceClient() {
        // 创建客户端factory
        ClientProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());
        // 设置接口类
        factory.setServiceClass(OSBBPWFPHQImportConfirmNotificationSrv.class);
        // 设置服务端点地址
//        String endpointUrl = "http://172.16.194.158:8100/WFP/OSB_BP_WFP_HQ_ImportConfirmNotificationSrv.v0/proxy/OSB_BP_WFP_HQ_ImportConfirmNotificationSrv";
        String endpointUrl = "http://172.16.243.63:8100/SOA/OSB_BP_SOA_HQ_ImportConfirmNotificatRouteSrv.v0/proxy/OSB_BP_SOA_HQ_ImportConfirmNotificatRouteSrv?wsdl";
        factory.setAddress(endpointUrl);
        OSBBPWFPHQImportConfirmNotificationSrv serviceClient = (OSBBPWFPHQImportConfirmNotificationSrv) factory.create();
        // 客户端超时设置
        Client proxy = ClientProxy.getClient(serviceClient);
        HTTPConduit http = (HTTPConduit) proxy.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        // 请求时间设置
        httpClientPolicy.setConnectionTimeout(3000);
        // 响应时间设置
        httpClientPolicy.setReceiveTimeout(60000);
        http.setClient(httpClientPolicy);
//        httpClientPolicy.setContentType("application/xml;charset=UTF-8");
        return serviceClient;
    }

    public static void main(String args[]) throws Exception {
        // 设置服务请求对象
        InputParameters inputParameters = buildMSGHEADER("11","22");
        // 设置服务客户端对象
        OSBBPWFPHQImportConfirmNotificationSrv port = buildServiceClient();
        // 调用服务接口
        OutputParameters response = port.process(inputParameters);
        // 输出服务调用结果
        System.err.println("返回："+response.toString());
        System.out.println(response.getBIZRETURNMESSAGE());
    }

}
